package perform.connection;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import perform.exception.ConnectionException;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class ConnectionManager {
	
	private ComboPooledDataSource dataSource;
	private Connection startupConnection;
	
	public ConnectionManager(String host, String port, String database, 
			String username, String password, String minPoolSize, 
			String acquireIncrement, String maxPoolSize) throws ConnectionException{
		try {
			String url = "jdbc:mysql://" + host + ":" + port;
			Class.forName("com.mysql.jdbc.Driver");
			startupConnection = DriverManager.getConnection(url, username, password);
			startupConnection.setAutoCommit(false);
			dataSource = new ComboPooledDataSource();
			dataSource.setDriverClass("com.mysql.jdbc.Driver");
			dataSource.setJdbcUrl(url + "/" + database);
			dataSource.setUser(username);
			dataSource.setPassword(password);
			dataSource.setMinPoolSize(Integer.parseInt(minPoolSize));
			dataSource.setMaxPoolSize(Integer.parseInt(maxPoolSize));
			dataSource.setAcquireIncrement(Integer.parseInt(acquireIncrement));
		} catch (PropertyVetoException e) {
			throw new ConnectionException("Can't load class 'com.mysql.jdbc.Driver'. Check if classpath contains `mysql-connector-java-5.X.XX-bin.jar`.", e);
		} catch (ClassNotFoundException e) {
			throw new ConnectionException("Can't load class 'com.mysql.jdbc.Driver'. Check if classpath contains `mysql-connector-java-5.X.XX-bin.jar`.", e);
		} catch (SQLException e) {
			throw new ConnectionException("Could not connect to MySQL server on `jdbc:mysql://" + host + ":" + port + "/`.", e);
		} catch (Exception e){
			throw new ConnectionException(e);
		}
	}
	
	public synchronized Connection getStartupConnection(){
		return startupConnection;
	}
	public synchronized Connection getConnection() throws SQLException{
		Connection connection = dataSource.getConnection();
		if(connection.getAutoCommit()){
			connection.setAutoCommit(false);
		}
		return connection;
	}
	public synchronized void close() throws SQLException{
		startupConnection.close();
		dataSource.close();
	}

}
